const uniSetStorageSync = uni.setStorageSync
const uniRemoveStorageSync = uni.removeStorageSync
const uniGetStorageSync = uni.getStorageSync

const refCache = {}
const watchListener = {}

uni.getStorageSync = key => {
    const storageInfo = uni.getStorageInfoSync()
    for (let storageKey of storageInfo.keys) {
        if (storageKey === key) {
            return uniGetStorageSync(key)
        }
    }
    return null
}

uni.removeStorageSync = key => {
    if (refCache[key]) {
        refCache[key].value = null
    }
    
    if (watchListener[key]) {
        watchListener[key].forEach(callback => callback(null))
    }
    
    return uniRemoveStorageSync(key)
}

uni.setStorageSync = (key, value) => {
    if (refCache[key]) {
        refCache[key].value = value
    }
    
    if (watchListener[key]) {
        watchListener[key].forEach(callback => callback(value))
    }
    
    if (value == null) {
        return uniRemoveStorageSync(key)
    } else {
        return uniSetStorageSync(key, value)
    }
}

const storageRef = (key, defValue) => {
    if (refCache[key]) {
        return refCache[key]
    }
    refCache[key] = ref(uni.getStorageSync(key) ?? defValue)
    watch(() => JSON.stringify(refCache[key].value), val => {
        uniSetStorageSync(key, JSON.parse(val))
    })
    return refCache[key]
}

const watchValue = (key, callback, options) => {
    if (watchListener[key] == null) {
        watchListener[key] = []
    }
    watchListener[key].push(callback)
    if (options && options.immediate) {
        callback(uni.getStorageSync(key))
    }
}

const get = (key, defValue) => {
    return uni.getStorageSync(key) ?? defValue
}

const set = (key, value) => {
    uni.setStorageSync(key, value)
}

const del = key => {
    uni.removeStorageSync(key)
}

export default {
    get, set, del, storageRef, watchValue,
    token: 'token', // token
    user: 'user', // 用户信息
    login: 'login', // 是否登录
}
